package org.xw.controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xw.dto.MsgDTO;
import org.xw.pojo.MessagePojo;
import org.xw.service.MessageService;
import org.xw.utils.ResponseUtil;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    MessageService service;

    @PostMapping("/upload")
    public ResponseUtil upFile(@RequestPart("chatFile") MultipartFile chatFile, @RequestPart("msgDTO") MessagePojo msgDTO) {
        System.out.println(msgDTO.toString());
        File filePath = new File("E:\\chat\\upload\\" + msgDTO.getUserId() + "\\file");
        boolean exists = filePath.exists();
        System.out.println(exists);
        if (!filePath.exists()) {
            boolean mkdir = filePath.mkdirs();
            System.out.println(mkdir);
        }
        // 生成随机文件名
        String filename = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(chatFile.getOriginalFilename());
        File newFile = new File(filePath, filename);
        // 保存文件到本地磁盘
        try {
            chatFile.transferTo(newFile);
            String databasePath = "http://93ex15636hn2.vicp.fun/image/" + msgDTO.getUserId() + "/file/" + filename;
            msgDTO.setFile(databasePath);

            //存消息，回头完善
//            int store = service.store(msgDTO);
//            if (store != 0) {
//                return ResponseUtil.success("存入成功");
//            } else return ResponseUtil.error("上传失败");
            return ResponseUtil.success(databasePath);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseUtil.error("上传失败");
        }
    }
}
